/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.diagram.activity.editpart;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.tools.CellEditorLocator;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.uml2.uml.Action;
import org.eclipse.uml2.uml.ControlFlow;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.ElementImport;
import org.eclipse.uml2.uml.NamedElement;

import com.cea.papyrus.core.PapyrusMessages;
import com.cea.papyrus.core.PapyrusPlugin;
import com.cea.papyrus.core.directedit.ILabelControler;
import com.cea.papyrus.core.directedit.LabelCellEditorLocator;
import com.cea.papyrus.core.directedit.LabelControler;
import com.cea.papyrus.core.directedit.LabelDirectEditManager;
import com.cea.papyrus.core.directedit.PropertyAccessor;
import com.cea.papyrus.core.editor.ModelManager;
import com.cea.papyrus.core.editor.mouseoveraction.ActionHandleManager;
import com.cea.papyrus.core.editpart.ContainerHighlightEditPolicy;
import com.cea.papyrus.core.editpart.ContainerWithSemanticEditPart;
import com.cea.papyrus.core.figures.IconFigure;
import com.cea.papyrus.core.ui.dialogs.PapyrusMessageDialog;
import com.cea.papyrus.core.utils.Debug;
import com.cea.papyrus.diagram.activity.figure.ActionFigure;
import com.cea.papyrus.diagraminterchange2.di2.GraphNode;
import com.cea.papyrus.diagraminterchange2.di2.Uml1SemanticModelBridge;

/**
 * Controller of an Action
 *
 * @author Gilles Cannenterre
 * @since 23 mars 07
 */
public class ActionEditPart extends ContainerWithSemanticEditPart {


	/**
	 * Manager for editing classname.
	 */
	protected DirectEditManager manager;

	/**
	 * The Constructor.
	 * 
	 * @param modelManager the model manager
	 * @param graphNode the graph node
	 */
	public ActionEditPart(GraphNode graphNode, ModelManager modelManager) {
		super(graphNode, modelManager);
	}

	/**
	 * Creates the figure.
	 * 
	 * @return the I figure
	 */
	@Override
	protected IFigure createFigure() {
		// Force initialization of the manager when figure has changed
		manager = null;		
		// Try to get figure from GraphNodeWithSemanticEditPart
		IFigure fig = super.createFigure();
		if (fig != null) {
			return fig;
		}
		return new ActionFigure();
	}

	/**
	 * Returns the Name Label of this as a PackageEdit part.
	 * 
	 * @return Label
	 */
	protected Label getNameLabel() {
		IFigure fig = getFigure();

		if (fig instanceof IconFigure) {
			return (Label) fig;
		} else if (fig instanceof ActionFigure) {
			return ((ActionFigure)fig).getNameLabel();
		} else {
			Debug.error(this, "ActionEditPart::getNameLabel() : Unknown Figure type.", channel);
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#getUmlElement()
	 */
	@Override
	public Action getUmlElement() {
		Element e = ((Uml1SemanticModelBridge)getGraphNode().getSemanticModel()).getElement();
		// Case of element import
		if(e instanceof ElementImport){
			return (Action)((ElementImport) e).getImportedElement();
		}
		// This is a simple Action
		return (Action)e;
	}

	/**
	 * Install Action handles for this editPart. Use same toolEntries than in
	 * palette
	 */
	protected void installActionHandle() {
		// Install mouse hover
		ActionHandleManager actionMngr = new ActionHandleManager(this);
		// Create a toolbar of actions.
		try {
			PaletteDrawer entries = new PaletteDrawer("creation tool");
			// Add shortcuts on actor figure for creating a association with an action
			entries.add(PapyrusPlugin.creationToolFactory
					.getConnectionCreationToolEntry(
							PapyrusMessages.AddControlFlowCommand_Label,
							PapyrusMessages.AddControlFlowCommand_Description,
							ControlFlow.class, null));
			actionMngr.addTool(entries, PositionConstants.EAST, false, 5);
		} catch (Exception e) {
			PapyrusMessageDialog.display(e.getMessage(), e);
		}
	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#refreshVisuals()
	 */
	@Override
	protected void refreshVisuals() {
		Debug.debug(this, "refreshVisuals()", channel);

		Dimension size = getGraphNode().getSize();
		Point p = getGraphNode().getPosition();
		Rectangle r = new Rectangle(p, size);
		
		IFigure fig = getFigure();

		// Classifier
		if (fig instanceof IconFigure) {
			IconFigure icf = (IconFigure) getFigure();
			icf.setName(((NamedElement) getUmlElement()).getName());
		} else {
			Action currentAction = getUmlElement();
			com.cea.papyrus.umlutils.Element currentElement = new com.cea.papyrus.umlutils.Element(getUmlElement());
			((ActionFigure) fig).refreshColors(getGraphNode());
			((ActionFigure) fig).refreshPresentation(getPresentation(),currentAction, getGraphNode());
			
			boolean hasIcon = currentElement.hasIcon();
			boolean hasShape = currentElement.hasShape();
		
			((ActionFigure) fig).refreshStereotypes(((ActionFigure) fig).stereotypesLabel(this), getPresentation(), hasIcon, hasShape);
			((ActionFigure) fig).setName(currentAction.getName());

			// qualifiedName
			GraphNode gp= (GraphNode) getGraphNode().getContainer();
			((ActionFigure) fig).refreshQualifiedName(gp, getGraphNode(), getUmlElement());
		}  

		((GraphicalEditPart) getParent()).setLayoutConstraint(this, fig, r);
	}
	
	/**
	 * the direct edit mechanism requires the edit part to handle the direct edit
	 * request.
	 * 
	 * @param req the request that called the direct edit.
	 */
	public void performDirectEdit(Request req) {
		initLabelEditManager();
		manager.show();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.editparts.AbstractEditPart#performRequest(org.eclipse.gef.Request)
	 */
	@Override
	public void performRequest(Request request){
		if (RequestConstants.REQ_DIRECT_EDIT.equals(request.getType())) {
			performDirectEdit(request);
		}
	}

	/**
	 * Init the label direct edit manager.
	 * This method should be called when a Direct Edit request is performed.
	 */
	protected void initLabelEditManager() {
		if(manager==null) {
			// locator for the cell editor (on the name label)
			CellEditorLocator locator = new LabelCellEditorLocator(getNameLabel());
	
			// defining how properties are modified in the model
			PropertyAccessor accessor = new PropertyAccessor() {
				public String getPropertyName() {
					return "Name";
				}
	
				public String getValue() {
					if(isElementImport()){
						return getElementImport().getAlias();
					}
					return getUmlElement().getName();
				}
				public void setValue(String value) {
					if(isElementImport()){
						getElementImport().setAlias(value);
					}
					else{getUmlElement().setName(value);}  
				}
			};
			// defines the controler: link between model and view
			ILabelControler labelControler = new LabelControler(getNameLabel(), accessor);
	
			// creates the editing manager.
			manager = new LabelDirectEditManager(this, locator, labelControler);
		}
	}

	/* (non-Javadoc)
	 * @see com.cea.papyrus.core.common.editpart.GraphNodeWithSemanticEditPart#createEditPolicies()
	 */
	@Override
	protected void createEditPolicies() {
		super.createEditPolicies();
		installEditPolicy(EditPolicy.SELECTION_FEEDBACK_ROLE,new ContainerHighlightEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new ActivityDiagramLayoutEditPolicy((XYLayout)getContentPane().getLayoutManager()));
		installActionHandle();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#getContentPane()
	 */
	/**
	 * 
	 * 
	 * @return 
	 */
	@Override
	public IFigure getContentPane() {
		if (getFigure() instanceof ActionFigure) {
			return ((ActionFigure) getFigure()).getContentPane();
		} else {
			// Figure is a shape
			return getFigure();
		}
	}
}